package com.chao.lease.web.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.chao.lease.common.constant.RedisConstant;
import com.chao.lease.common.exception.LeaseException;
import com.chao.lease.common.result.ResultCodeEnum;
import com.chao.lease.common.utils.JwtUtil;
import com.chao.lease.model.entity.SystemUser;
import com.chao.lease.model.entity.UserInfo;
import com.chao.lease.model.enums.BaseStatus;
import com.chao.lease.web.admin.mapper.SystemUserMapper;
import com.chao.lease.web.admin.service.LoginService;
import com.chao.lease.web.admin.service.SystemUserService;
import com.chao.lease.web.admin.service.UserInfoService;
import com.chao.lease.web.admin.vo.login.CaptchaVo;
import com.chao.lease.web.admin.vo.login.LoginVo;
import com.wf.captcha.GifCaptcha;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SystemUserMapper systemUserMapper;

    @Override
    public CaptchaVo getCaptcha() {

        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);

        String code = specCaptcha.text().toLowerCase();
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();

        redisTemplate.opsForValue().set(key,code, RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);
        return new CaptchaVo(specCaptcha.toBase64(),key);
    }

    @Override
    public String login(LoginVo loginVo) {
        // 1.判断`captchaCode`是否为空，若为空，则直接响应`验证码为空`；若不为空进行下一步判断。
        if(!StringUtils.hasText(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }

        // 2.根据`captchaKey`从Redis中查询之前保存的`code`，若查询出来的`code`为空，则直接响应`验证码已过期`；若不为空进行下一步判断
        String dateCode = redisTemplate.opsForValue().get(loginVo.getCaptchaKey());
        String userCode = loginVo.getCaptchaCode().toLowerCase();

        if(dateCode == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }

        // 3.比较`captchaCode`和`code`，若不相同，则直接响应`验证码不正确`；若相同则进行下一步判断。
        if(!dateCode.equals(userCode)){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_ERROR);
        }

        // - 根据`username`查询数据库，若查询结果为空，则直接响应`账号不存在`；若不为空则进行下一步判断。
        SystemUser systemUser = systemUserMapper.getByUserName(loginVo.getUsername());


        if (systemUser == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        // - 查看用户状态，判断是否被禁用，若禁用，则直接响应`账号被禁`；若未被禁用，则进行下一步判断。
        if(systemUser.getStatus() != BaseStatus.ENABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }
        // - 比对`password`和数据库中查询的密码，若不一致，则直接响应`账号或密码错误`，若一致则进行入最后一步。

        String userPassword = DigestUtils.md5Hex(loginVo.getPassword());
        String datePassword = systemUser.getPassword();

        if(!userPassword.equals(datePassword)){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        // - 创建JWT，并响应给浏览器。
        return JwtUtil.createToken(systemUser.getId(),systemUser.getUsername());
    }
}
